package com.chalk.config.security;

import com.chalk.config.security.filter.CustomFilterSecurityInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;

/**
 * ClassName: ResourceServerConfig
 *
 * @author L.G
 * @Description Resource Server 配置
 * @email lg10000@126.com
 * @date 2018年8月1日 下午3:10:59
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private FilterIgnoreAuthenticateConfig filterIgnoreAuthenticateConfig;

    @Autowired
    private CustomAuthExceptionEntryPoint authExceptionEntryPoint;

    @Autowired
    private CustomAccessDeniedHandler customAccessDeniedHandler;

    @Autowired
    private CustomFilterSecurityInterceptor myFilterSecurityInterceptor;


    @Override
    public void configure(HttpSecurity http) throws Exception {
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http
                .authorizeRequests();
        /* 忽略认证资源  */
        filterIgnoreAuthenticateConfig.getUrls().forEach(url -> {
            registry.antMatchers(url).permitAll();
        });
        /* 除上面外的所有请求全部需要鉴权认证 */
        registry.anyRequest().authenticated();
        /*跨域请求拦截处理*/
        http.addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class);
    }

    /**
     * 配置自定义异常
     *
     * @param resources
     * @throws Exception
     */
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.authenticationEntryPoint(authExceptionEntryPoint)
                .accessDeniedHandler(customAccessDeniedHandler);
    }
}
